package serversidepkg;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import backendpkg.DataSource;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

/**
 * Servlet implementation class CreateChat
 */
public class CreateChat extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateChat() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
			response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
			response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
			response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
			
			//Get username from session
			HttpSession session = request.getSession();			
            String user = (String) session.getAttribute("username");

            if (user == null) {
               request.setAttribute("Error", "Session has ended.  Please login.");
               RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
               rd.forward(request, response);
            }else{
            
	            //Get Parameters from request
	            String accepted = request.getParameter("accept");
	            String sender = request.getParameter("sender");
	            
	            //Prepare xml string
	            String xml="<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><root>";
	            
	            //Get connection to database
	            DataSource datasource = new DataSource();
	            Connection conn = datasource.getConnection();
	            PreparedStatement statement;
	            
	            if(accepted.equals("true")) 
	            {	
	            	            	
	            	//Create new chat
		            String insert ="INSERT INTO Chat (user1, user2)"
		                    +" VALUES (?,?)";
		            
		            statement = (PreparedStatement) conn.prepareStatement(insert);
		            statement.setString(1, sender);
		            statement.setString(2, user);
		            statement.executeUpdate();
		            
		            //Take id of created chat
		            String idquery = "SELECT chat_id FROM Chat WHERE user1=? AND user2=?";
		            statement = (PreparedStatement) conn.prepareStatement(idquery);
		            statement.setString(1, sender);
		            statement.setString(2, user);
		            //statement.setString(3, user);
		            //statement.setString(4, sender);
		        
		            ResultSet result = statement.executeQuery();
		            int id = 0;
		            
		            while(result.next())
		            {
		            	id = result.getInt("chat_id");
		                xml+="<chat_id>" + id + "</chat_id>";
		                xml+="<requestor>" + sender +"</requestor>";
		            }
		            xml+="</root>";
		            
		            //Insert id of created chat into Incoming and set accepted=true
		            String updateinc ="UPDATE Incoming SET accepted=?,newchatID=? WHERE sender=? AND receiver=?";
	                
	                statement = (PreparedStatement) conn.prepareStatement(updateinc);
	                statement.setString(1,"true");
	                statement.setString(2, ""+id);
	                statement.setString(3, sender);
	                statement.setString(4, user);
	                statement.executeUpdate();
		            
	            }else{
	            	//Set accepted false in Incoming
	                String updateinc ="UPDATE Incoming set accepted=? WHERE sender=? AND receiver=?";
	                
	                statement = (PreparedStatement) conn.prepareStatement(updateinc);
	                statement.setString(1, "false");
	                statement.setString(2, sender);
	                statement.setString(3, user);
	                statement.executeUpdate();
	                
	            }        
	            response.getWriter().write(xml);
	            conn.close();
            }
        } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
            
        }
	}

}